//
//  ScrollTabControl.m
//  danpin
//
//  Created by chuangjia on 25/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "ScrollTabControl.h"
#define ScrollTabControlMenuHeight     (40)

@implementation TabMenuItem
@synthesize titleLabel=_titleLabel;

-(id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        _titleLabel = [[UILabel alloc] initWithFrame:self.bounds];
        _titleLabel.font =FONT(14);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor grayColor];
        [self addSubview:_titleLabel];
    }
    return self;
   
}
-(void)dealloc
{
    self.titleLabel=nil;
}
@end

@interface ScrollTabControl()<UITableViewDataSource,UITableViewDelegate>

/** @brief 顶部菜单栏横向滑动的table */
@property (nonatomic, strong) UITableView *topMenuTableView;

/** @brief 菜单下面横向滑动内容的table */
@property (nonatomic, strong) UITableView *contentTableView;
@property (nonatomic, assign) NSInteger selectedIndex;

@end


@implementation ScrollTabControl
@synthesize selectedIndex=_selectedIndex;

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        _selectedIndex=0;
    }
    return self;
}


- (void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(handleEndScroll) object:nil];
}

#pragma mark - UIKIT




#pragma mark - override

- (UITableView *)topMenuTableView
{
    if(nil == _topMenuTableView)
    {
        CGFloat topMenuHeight = ScrollTabControlMenuHeight;
        
        //before rotate bounds = (0, 0, width, height)  , rototate -90 bounds = (0, 0, height, width)
        CGFloat x = CGRectGetWidth(self.frame)/2 - topMenuHeight/2;
        CGFloat y = -CGRectGetWidth(self.frame)/2 + topMenuHeight/2;
        CGRect topMenuRect = CGRectMake(x, y, topMenuHeight, CGRectGetWidth(self.frame));
        _topMenuTableView = [[UITableView alloc] initWithFrame:topMenuRect
                                                         style:UITableViewStylePlain];
        [self addSubview:_topMenuTableView];
        _topMenuTableView.backgroundColor = [UIColor whiteColor];
        _topMenuTableView.dataSource = self;
        _topMenuTableView.delegate = self;
        _topMenuTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _topMenuTableView.showsVerticalScrollIndicator = NO;
        _topMenuTableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
        _topMenuTableView.scrollsToTop = NO;
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, ScrollTabControlMenuHeight-0.5,CGRectGetWidth(self.frame), 0.5)];
        lineView.backgroundColor = UIColorFromRGB(0xe5e5e5);
        [self addSubview:lineView];
        lineView = nil;
    }
    return _topMenuTableView;
}


- (UITableView *)contentTableView
{
    if(nil == _contentTableView)
    {
        CGFloat contentHeight = CGRectGetWidth(self.frame);
        CGFloat contentWidth  = CGRectGetHeight(self.frame) - ScrollTabControlMenuHeight;
        CGFloat x = CGRectGetWidth(self.frame)/2 - contentWidth/2;
        CGFloat y = (CGRectGetHeight(self.frame) - ScrollTabControlMenuHeight)/2 - contentHeight/2 + (ScrollTabControlMenuHeight);
        CGRect contentRect = CGRectMake(x, y, contentWidth, contentHeight);
        _contentTableView = [[UITableView alloc] initWithFrame:contentRect
                                                         style:UITableViewStylePlain];
        [self addSubview:_contentTableView];
        
        _contentTableView.backgroundColor = [UIColor whiteColor];
        _contentTableView.dataSource = self;
        _contentTableView.delegate = self;
        _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _contentTableView.showsVerticalScrollIndicator = NO;
        _contentTableView.pagingEnabled = YES;
        _contentTableView.transform = CGAffineTransformMakeRotation(-M_PI / 2);
        _contentTableView.scrollsToTop = NO;
    }
    
    return _contentTableView;
}


#pragma mark - UITableView Datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([self.datasource respondsToSelector:@selector(ScrollTabControlMenuCount:)])
    {
        return [self.datasource ScrollTabControlMenuCount:self];
    }
    return 0;
}

- (UITableViewCell*)getErrorcell:(UITableView*)tableView
{
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"ErrorEmptyCell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ErrorEmptyCell"];
    }
    return  cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    if(tableView == self.topMenuTableView)
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TabMenuItem"];//之前为什么不重用cell
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TabMenuItem"];
            cell.frame = CGRectMake(0,0,ScrollTabControlMenuHeight,[self getMenuWidth:indexPath.row]);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [[cell.contentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
        if([self.datasource respondsToSelector:@selector(ScrollTabControl:itemAtIndex:)])
        {
            TabMenuItem *item = [self.datasource ScrollTabControl:self itemAtIndex:indexPath.row];
            
            CGFloat x = (ScrollTabControlMenuHeight- CGRectGetWidth(item.frame))/2;
            CGFloat y = ([self getMenuWidth:indexPath.row] - CGRectGetHeight(item.frame))/2;
            item.frame = CGRectMake(x, y, CGRectGetWidth(item.frame), CGRectGetHeight(item.frame));
            item.transform = CGAffineTransformMakeRotation(M_PI / 2);
            cell.contentView.backgroundColor = [UIColor whiteColor];
            if (_selectedIndex == indexPath.row) {
                item.titleLabel.textColor = RED_COLOR;
            }else{
                item.titleLabel.textColor = [UIColor grayColor];
            }
            [cell.contentView addSubview:item];
            item=nil;
            
        }
        return cell;
        
    }
    
    if(tableView == _contentTableView)
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContentPageCell"];
        
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ContentPageCell"];
            cell.frame = CGRectMake(0, 0, CGRectGetHeight(self.frame) - ScrollTabControlMenuHeight, CGRectGetWidth(self.frame));
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [[cell.contentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
        if([self.datasource respondsToSelector:@selector(ScrollTabControl:pageAtIndex:)])
        {
            UIView *page = [self.datasource ScrollTabControl:self pageAtIndex:indexPath.row];
            
            CGFloat x = (CGRectGetWidth(cell.frame) - CGRectGetWidth(page.frame))/2;
            CGFloat y = (CGRectGetHeight(cell.frame) - CGRectGetHeight(page.frame))/2;
            page.frame = CGRectMake(x, y, CGRectGetWidth(page.frame), CGRectGetHeight(page.frame));
            page.transform = CGAffineTransformMakeRotation(M_PI / 2);
            cell.contentView.backgroundColor = [UIColor whiteColor];
            [cell.contentView addSubview:page];
            page=nil;
        }
        return cell;
        
    }
    
    return  [self getErrorcell:tableView];
 //   return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.topMenuTableView)
    {
        return [self getMenuWidth:indexPath.row];
    }
    
    if (tableView == self.contentTableView) {
        return CGRectGetWidth(self.frame);
    }
    return 0;
}



#pragma mark - UItableView Delegate


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.contentTableView)
    {
        NSUInteger tempPage = (self.contentTableView.contentOffset.y + 0.5*CGRectGetWidth(self.frame))/CGRectGetWidth(self.frame);
        if(tempPage != self.pageIndex)
            _pageIndex = tempPage;
//        NSLog(@"==========scrollViewDidScroll==%ld==%ld",tempPage,self.pageIndex);
        _selectedIndex = tempPage;
    }
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView == self.contentTableView)
    {
        [self handleEndScroll];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(scrollView == self.contentTableView)
    {
        if(!decelerate)
        {
            [self handleEndScroll];
        }
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.topMenuTableView)
    {
        _selectedIndex = indexPath.row;
        [self contentTablesSrollToIndexPath:indexPath];
    }
}

#pragma mark - public method

- (void)reloadData
{
    [self.topMenuTableView reloadData];
    [self.contentTableView reloadData];
}

- (void)displayPageAtIndex:(NSUInteger)pageIndex
{
    _selectedIndex = pageIndex;
    [self contentTablesSrollToIndexPath:[NSIndexPath indexPathForRow:pageIndex inSection:0]];
}

#pragma mark - private method
/**
 *  得到顶部菜单栏单个菜单的宽度
 *
 *  @return 宽度
 */
- (CGFloat)getMenuWidth:(NSUInteger)index
{
    
    if([self.datasource respondsToSelector:@selector(ScrollTabControlWidth:itemAtIndex:)])
    {
        return [self.datasource ScrollTabControlWidth:self itemAtIndex:index];
    }
    return 0;
}


/**
 *  page table 停止滚动的时候
 */
- (void)handleEndScroll
{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.pageIndex inSection:0];
    [self.topMenuTableView scrollToRowAtIndexPath:indexPath
                                 atScrollPosition:UITableViewScrollPositionMiddle
                                         animated:YES];
    _selectedIndex = indexPath.row;
    [self.topMenuTableView reloadData];
}


/**
 *  <#Description#>
 *
 *  @param indexPath <#indexPath description#>
 */
- (void)contentTablesSrollToIndexPath:(NSIndexPath *)indexPath
{
    _selectedIndex = indexPath.row;
    [self.contentTableView scrollToRowAtIndexPath:indexPath
                                 atScrollPosition:UITableViewScrollPositionMiddle
                                         animated:NO];
    [self performSelector:@selector(handleEndScroll) withObject:nil afterDelay:0.25];
}




/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
